import 'package:flutter/material.dart';
import '../controls/basic/e_card.dart';
import '../controls/basic/e_table.dart';

// 通道数据模型 - 移到顶层定义
class Channel {
  final String id;
  bool isOn;
  final String color;
  final String bdNumber;
  final String testDescription;
  final String group;
  final String measurementType;
  final String unit;
  final double rangeValue;
  final String dfePass;
  final String ratio;
  final double currentValue;
  final double maxValue;
  final double minValue;

  Channel({
    required this.id,
    required this.isOn,
    required this.color,
    required this.bdNumber,
    required this.testDescription,
    required this.group,
    required this.measurementType,
    required this.unit,
    required this.rangeValue,
    required this.dfePass,
    required this.ratio,
    required this.currentValue,
    required this.maxValue,
    required this.minValue,
  });

  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'isOn': isOn,
      'color': color,
      'bdNumber': bdNumber,
      'testDescription': testDescription,
      'group': group,
      'measurementType': measurementType,
      'unit': unit,
      'rangeValue': rangeValue,
      'dfePass': dfePass,
      'ratio': ratio,
      'currentValue': currentValue,
      'maxValue': maxValue,
      'minValue': minValue,
    };
  }
}

class ChannelSettingPage extends StatefulWidget {
  const ChannelSettingPage({super.key});

  @override
  State<ChannelSettingPage> createState() => _ChannelSettingPageState();
}

class _ChannelSettingPageState extends State<ChannelSettingPage> {
  // 通道列表
  List<Channel> channels = [];
  
  // 表格列定义
  List<ETableColumn<Channel>> _columns = [];

  // 初始化通道数据
  @override
  void initState() {
    super.initState();
    _initializeChannels();
    _initializeColumns();
  }

  // 初始化表格列配置
  void _initializeColumns() {
    _columns = [
      ETableColumn(
        prop: 'id',
        label: '通道',
        width: 80,
      ),
      ETableColumn(
        prop: 'isOn',
        label: '开关',
        width: 60,
        render: (context, row, index) {
          return Switch(
            value: row.isOn,
            onChanged: (bool value) => _toggleChannel(index),
            activeColor: Colors.green,
            inactiveThumbColor: Colors.grey,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          );
        },
      ),
      ETableColumn(
        prop: 'balance',
        label: '平衡器',
        width: 80,
        render: (context, row, index) {
          return row.isOn 
            ? Row(
                children: [
                  Icon(Icons.balance, size: 16, color: Colors.blue),
                  SizedBox(width: 4),
                  Text('平', style: TextStyle(fontSize: 12)),
                ],
              )
            : Container();
        },
      ),
      ETableColumn(
        prop: 'color',
        label: '颜色',
        width: 60,
        render: (context, row, index) {
          return Container(
            width: 30,
            height: 30,
            decoration: BoxDecoration(
              color: Color(int.parse('0xFF${row.color}')),
              borderRadius: BorderRadius.circular(4),
              border: Border.all(color: Colors.grey),
            ),
          );
        },
      ),
      ETableColumn(
        prop: 'bdNumber',
        label: 'BD号',
        width: 80,
      ),
      ETableColumn(
        prop: 'testDescription',
        label: '测试描述',
        width: 120,
      ),
      ETableColumn(
        prop: 'group',
        label: '分组',
        width: 80,
      ),
      ETableColumn(
        prop: 'measurementType',
        label: '测量类型',
        width: 100,
      ),
      ETableColumn(
        prop: 'unit',
        label: '单位',
        width: 60,
      ),
      ETableColumn(
        prop: 'range',
        label: '范围',
        width: 100,
        render: (context, row, index) {
          return Text('${row.rangeValue}${row.unit}', style: TextStyle(fontSize: 12));
        },
      ),
      ETableColumn(
        prop: 'dfePass',
        label: 'DFE-PASS',
        width: 100,
      ),
      ETableColumn(
        prop: 'ratio',
        label: '比例',
        width: 100,
      ),
      ETableColumn(
        prop: 'status',
        label: '实时状态',
        width: 200,
        render: (context, row, index) {
          return row.isOn
            ? Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '当前值: ${row.currentValue.toStringAsFixed(3)}${row.unit}',
                    style: TextStyle(fontSize: 12),
                  ),
                  Text(
                    '范围: ${row.minValue} ~ ${row.maxValue}${row.unit}',
                    style: TextStyle(fontSize: 10, color: Colors.grey),
                  ),
                  // 简单的进度条
                  Container(
                    height: 4,
                    width: 180,
                    margin: EdgeInsets.only(top: 4),
                    decoration: BoxDecoration(
                      color: Colors.grey[200],
                      borderRadius: BorderRadius.circular(2),
                    ),
                    child: Container(
                      width: 180 * ((row.currentValue - row.minValue) / (row.maxValue - row.minValue)),
                      height: 4,
                      decoration: BoxDecoration(
                        color: row.currentValue > 0 ? Colors.red : Colors.blue,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                  ),
                ],
              )
            : Text(
                '通道已关闭',
                style: TextStyle(fontSize: 12, color: Colors.grey),
              );
        },
      ),
    ];
  }

  // 初始化16个通道的数据
  void _initializeChannels() {
    // 创建颜色列表
    final List<String> colors = [
      'FF0000', '0000FF', '00FF00', 'FFFF00',
      'FF00FF', '00FFFF', '800000', '808000',
      '008000', '800080', '008080', '000080',
      '808080', 'C0C0C0', 'FFA500', 'FFC0CB'
    ];

    // 创建16个通道
    for (int i = 1; i <= 16; i++) {
      final int index = i - 1;
      final double randomValue = -10000 + (20000 * (index / 15));
      
      channels.add(Channel(
        id: '1-${i.toString().padLeft(2, '0')}',
        isOn: true,
        color: colors[index],
        bdNumber: '未标定',
        testDescription: '',
        group: '电压',
        measurementType: '电压测量',
        unit: 'mV',
        rangeValue: 10000,
        dfePass: 'DFE - PASS',
        ratio: '1 mV/mV',
        currentValue: randomValue,
        maxValue: 10000,
        minValue: -10000,
      ));
    }
  }

  // 切换通道开关状态
  void _toggleChannel(int index) {
    setState(() {
      channels[index].isOn = !channels[index].isOn;
    });
  }

  // 保存通道设置
  void _saveSettings() {
    // 这里可以实现保存通道设置的逻辑
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('通道设置已保存')),
    );
  }

  // 重置通道设置
  void _resetSettings() {
    setState(() {
      channels.forEach((channel) {
        channel.isOn = true;
      });
    });
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('通道设置已重置')),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ETable<Channel>(
        data: channels,
        columns: _columns,
        border: true,
        striped: true,
        hoverable: true,
        showHeader: true,
        rowKey: 'id',
        size: 'small',
    );
  }
}